package com.bxw.forum.service.impl;


import com.bxw.forum.common.AppResult;
import com.bxw.forum.common.ResultCode;
import com.bxw.forum.dao.ArticleMapper;
import com.bxw.forum.exception.ApplicationException;
import com.bxw.forum.model.Article;
import com.bxw.forum.model.Board;
import com.bxw.forum.model.User;
import com.bxw.forum.model.UserLike;
import com.bxw.forum.service.IArticleService;
import com.bxw.forum.service.IBoardService;
import com.bxw.forum.service.IUserLikeService;
import com.bxw.forum.service.IUserService;
import com.bxw.forum.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    ArticleMapper articleMapper;

    @Resource
    IUserLikeService userLikeService;
    @Resource
    IBoardService boardService;

    @Resource
    IUserService userService;


    /**
     * 新增帖子
     * @param article 帖子对象
     */
    @Override
    public void create(Article article) {

        if(article == null
                || article.getBoardId() == null
                || article.getUserId() == null
                || StringUtils.isEmpty(article.getTitle())
                || StringUtils.isEmpty(article.getContent())) {

            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }


        article.setVisitCount(0);
        article.setLikeCount(0);
        article.setReplyCount(0);
        article.setState((byte)0);
        article.setDeleteState((byte)0);

        Date date = new Date();
        article.setUpdateTime(date);
        article.setCreateTime(date);

        //将新建帖子插入数据库
        int row = articleMapper.insertSelective(article);

        if(row <= 0) {
            log.warn(ResultCode.FAILED_CREATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        //更新用户帖子数
        User user = userService.selectById(article.getUserId());

        if(user == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        userService.addOneArticleCountById(article.getUserId());

        //更新版块帖子数量
        Board board = boardService.selectById(article.getBoardId());

        if(board == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        boardService.addOneArticleCountById(article.getBoardId());

        //成功新增
        log.info(ResultCode.SUCCESS.toString() + ", user id = " + article.getUserId()
                + ", board id = " + article.getBoardId() + ", article id = "+article.getId() + "发帖成功");



    }

    /**
     * 首页查询(无参)所有版本下的所有帖子
     * @return List<Article>
     */
    @Override
    public List<Article> selectAll() {

        List<Article> articles = articleMapper.selectAll();

        return articles;
    }

    /**
     * 根据不同版块查询该板块下的文章
     * @param boardId 版块ID
     * @return List<Article>
     */
    @Override
    public List<Article> selectAllByBoardId(Long boardId) {

        if(boardId == null || boardId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Board board = boardService.selectById(boardId);

        if(board == null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        List<Article> articles = articleMapper.selectAllByBoardId(boardId);

        return articles;
    }


    /**
     * 根据文章ID关联查询文章详情
     * @param id 文章ID
     * @return Article
     */
    @Override
    public Article selectDetailById(Long id) {

        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        Article article = articleMapper.selectDetailById(id);

        if(article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        article.setVisitCount(article.getVisitCount() + 1);

        return article;
    }


    /**
     * 更新帖子
     * @param id 帖子ID
     * @param title 帖子标题
     * @param content 帖子内容
     */
    @Override
    public void modify(Long id, String title, String content) {

        if(id == null || id <= 0 || StringUtils.isEmpty(title) || StringUtils.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());

        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

    }

    /**
     * 根据文章ID(无关联)查询文章详情
     * @param id 帖子ID
     * @return Article
     */
    @Override
    public Article selectById(Long id) {

        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article article = articleMapper.selectByPrimaryKey(id);

        return article;
    }

    /**
     * 根据帖子ID修改点赞数
     * @param id 帖子ID
     */
    @Override
    public void thumbsUpById(Long id,Long userId) {

        //检查数据
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);

        //检查帖子状态是否正常
        if(article == null || article.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if(article.getState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //判断是否已经点赞
        UserLike userLike = userLikeService.selectById(userId, article.getId());

        if(userLike != null) {
            log.warn("已点赞");

            throw new ApplicationException(AppResult.fail("已点赞"));
        }

        //更新帖子中的点赞数量
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);

        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        //用户点赞后在则记录在表中
        userLikeService.insert(userId, article.getId());

        log.info("第一次点赞成功");
    }

    /**
     * 通过帖子ID删除对应的文章
     * @param id 帖子ID
     */
    @Override
    public void deleteById(Long id) {
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);

        //检查帖子状态是否正常
        if(article == null || article.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if(article.getState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //更新帖子中的删除状态
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte)1);

        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        //更新版块中文章数量
        boardService.subOneArticleCountById(article.getBoardId());
        //更新用户发帖数量
        userService.subOneArticleCountById(article.getUserId());

        log.info("删除帖子成功, article id = " + article.getId() + ", user id = " + article.getUserId() + ".");
    }

    /**
     * 根据帖子ID修改回复数量
     * @param id 帖子ID
     */
    @Override
    public void addOneReplyCountById(Long id) {
        //参数校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);

        //校验帖子状态
        if(article == null || article.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if(article.getState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //实现业务逻辑
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        //校验更新是否正常
        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        // 非空校验
        if (userId == null || userId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验用户是否存在
        User user = userService.selectById(userId);
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + userId);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 调用DAO
        List<Article> articles = articleMapper.selectByUserId(userId);
        // 返回结果
        return articles;
    }

}
